package web.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;

import web.servlet.dto.DtoFactory;
import data.model.User;

public class ConfirmationServlet extends AbstractJsonCapableServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String email = request.getParameter("email");
        final String token = request.getParameter("token");

        final User user = dataLayer.findUserByEmail(email);
        if (user == null) {
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid email address"), response);
        } else if (user.getConfirmationToken() == null || !user.getConfirmationToken().equals(token)) {
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid token"), response);
        } else {
            final String password = generateRandomPassword();
            user.setPassword(password);
            user.setConfirmationToken(null);
            dataLayer.updateObject(user);

            sendPasswordEmail(email, password);

            jsonHandler.writeAsJson(DtoFactory.createMessage("An email containing your password has been sent to your email address"), response);
        }
    }

    private String generateRandomPassword() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

    private void sendPasswordEmail(String email, String password) {
        final Map<String, String> mailTemplateParams = new HashMap<String, String>();
        mailTemplateParams.put("password.plainTextPassword", password);
        mailTemplateParams.put("password.loginUrl", HOST + "/index.jsp");

        emailLayer.sendEmail(email, "password.subject", "password.body", mailTemplateParams);
    }

}
